﻿using System;
using System.Reflection;
using NHibernate;

using System.IO;
using System.Xml;
using BotonJXC.Util;
using System.Resources;
using System.Collections;

namespace BotonJXC.DAO
{
    public class HBHelper
    {
        public static ISessionFactory SessionFactory;
        static NHibernate.Cfg.Configuration Config;
        static HBHelper()
        {
            InitLoad();
        }
        static void InitLoad()
        {
            try
            {
                Config = new NHibernate.Cfg.Configuration().Configure(XmlReaderDecrypt());
                LoadMappingFile();
                SessionFactory = Config.BuildSessionFactory();
            }
            catch (Exception ex)
            {
                //LogPools.Info(typeof(HBHelper), "連接失敗", ex);
                Console.WriteLine(ex);
            }
        }
        static void LoadMappingFile()
        {
            Assembly asm = Assembly.Load("BotonJXC.Entity");
            Config.AddAssembly(asm);
            //foreach (string resName in asm.GetManifestResourceNames())
            //{
            //    Console.WriteLine(resName);
            //    Stream stream = asm.GetManifestResourceStream(resName);
            //    Config.a
            //    //ResourceReader rr = new ResourceReader(stream);
            //    //IDictionaryEnumerator enumerator = rr.GetEnumerator();
            //    //while (enumerator.MoveNext())
            //    //{
            //    //    DictionaryEntry de = (DictionaryEntry)enumerator.Current;
            //    //    Console.WriteLine(de.Key);
            //    //    //de.Key是资源名
            //    //    //de.Value是资源内容
            //    //}
            //}
        }
        public static XmlReader XmlReaderDecrypt()
        {

            string c_SecKey = "19880501";
            string path = AppDomain.CurrentDomain.BaseDirectory + "NHibernate.cfg.xml";
            XmlDocument xd = new XmlDocument();
            xd.Load(path);
            XmlNode _dbNode;
            XmlNamespaceManager m = new XmlNamespaceManager(xd.NameTable);
            m.AddNamespace("ab", "urn:nhibernate-configuration-2.2");
            _dbNode = xd.DocumentElement.SelectSingleNode("//ab:property[@name='connection.connection_string']", m);
            string[] _con = _dbNode.InnerText.Split('=');
            //進行解密

            string tbxDBServer = null;
            string tbxDBName = null;
            string tbxDBUser = null;
            string tbxDBPass = null;

            try
            {
                tbxDBServer = Encoder.DESDecrypt(_con[2].Split(';')[0].ToString(), c_SecKey);
                tbxDBName = Encoder.DESDecrypt(_con[1].Split(';')[0].ToString(), c_SecKey);
                tbxDBUser = Encoder.DESDecrypt(_con[3].Split(';')[0].ToString(), c_SecKey);
                tbxDBPass = Encoder.DESDecrypt(_con[4].Split(';')[0].ToString(), c_SecKey);
            }
            catch
            {
                tbxDBServer = "沒有";
                tbxDBName = "沒有";
                tbxDBUser = "沒有";
                tbxDBPass = "沒有";
            }

            //string connectionString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};Charset=utf8", tbxDBName, tbxDBServer, tbxDBUser, tbxDBPass);
            //_dbNode.InnerText = connectionString;

            XmlReader xr = XmlReader.Create(new StringReader(xd.OuterXml));

            return xr;
        }

        public static ISession Session
        {
            get
            {
                if (SessionFactory == null)
                    InitLoad();
                if (SessionFactory != null)
                {
                    if (!NHibernate.Context.CurrentSessionContext.HasBind(SessionFactory))
                        NHibernate.Context.CurrentSessionContext.Bind(SessionFactory.OpenSession());
                    ISession session = SessionFactory.GetCurrentSession();
                    if (!session.IsConnected || !session.IsOpen)
                    {
                        session = SessionFactory.OpenSession();
                        NHibernate.Context.CurrentSessionContext.Bind(session);
                    }
                    return session;
                }
                else
                {
                    return null;
                }
            }
        }
        public static bool ConnectionEnabled
        {
            get
            {
                if (SessionFactory == null)
                    return false;
                try
                {
                    ISession ses = HBHelper.Session;
                    return true;
                }
                catch (System.Data.Common.DbException ex)
                {
                    //LogPools.Info(typeof(HBHelper), "連接失敗", ex);
                    return false;
                }
            }
        }
        public static void Reset()
        {
            InitLoad();
        }
        public static ITransaction BeginTransaction()
        {
            return Session.BeginTransaction();
        }
        public static void Commit()
        {
            Session.Transaction.Commit();
            Session.Close();
        }
        public static void Rollback()
        {
            if (Session.Transaction.IsActive)
                Session.Transaction.Rollback();
        }
        public static void Close()
        {
            if (!Session.Transaction.IsActive)
                Session.Close();
        }
        public static void Clear()
        {
            Session.Clear();
        }

        public string GetIdentifierPropertyName(Type type)
        {
            return HBHelper.SessionFactory.GetClassMetadata(type).IdentifierPropertyName;
        }
    }
}
